package vh.android.multiconnector.library;


import java.security.MessageDigest;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Encryption {

	private SecretKeySpec skeySpec;
	private Cipher cipher;
	private IvParameterSpec ivParameterSpec;

	public Encryption(byte[] keyraw) throws Exception {
		if (keyraw == null) {
			byte[] bytesOfMessage = "".getBytes("UTF-8");
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] bytes = md.digest(bytesOfMessage);

			skeySpec = new SecretKeySpec(bytes, "AES");
		} else {

			skeySpec = new SecretKeySpec(keyraw, "AES");
			cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

		}
	}

	public Encryption(String passphrase) throws Exception {
		byte[] bytesOfMessage = passphrase.getBytes("UTF-8");
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] thedigest = md.digest(bytesOfMessage);
		skeySpec = new SecretKeySpec(thedigest, "AES");

		cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

		// Initialisation vector:
		byte[] iv = new byte[16];
//		SecureRandom.getInstance("SHA1PRNG").nextBytes(iv); // If storing
		for(int i = 0; i < (passphrase.length() < iv.length?passphrase.length():iv.length); i++) {
			iv[i] = bytesOfMessage[i];
		}
		
		// separately
		ivParameterSpec = new IvParameterSpec(iv);
		cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	}

	public Encryption() throws Exception {
		byte[] bytesOfMessage = "".getBytes("UTF-8");
		MessageDigest md = MessageDigest.getInstance("MD5");
		byte[] thedigest = md.digest(bytesOfMessage);
		skeySpec = new SecretKeySpec(thedigest, "AES");

		skeySpec = new SecretKeySpec(new byte[16], "AES");
		cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	}

	public byte[] encrypt(byte[] plaintext) throws Exception {
		// returns byte array encrypted with key

		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);

		byte[] ciphertext = cipher.doFinal(plaintext);

		return ciphertext;
	}

	public byte[] decrypt(byte[] ciphertext) throws Exception {
		// returns byte array decrypted with key
		cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);

		byte[] plaintext = cipher.doFinal(ciphertext);

		return plaintext;
	}

}
